package com.gps.pe.base.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;

import com.gps.pe.model.Actions;
import com.gps.pe.model.Actions.ActionController;

/**
 * 1st level caching
 * Placement engine context listener class to load controller mappings
 * 
 * @author GPS
 *
 */
@WebListener
public class ControllerConfigLoaderListener implements ServletContextListener {
	private static final Logger LOGGER = Logger.getLogger(ControllerConfigLoaderListener.class);
	private static String PE_CONTROLLER_MAPPING_FILE = "\\classes\\com\\gps\\pe\\web\\PlacementEngineContext.xml";

	@Override
	public void contextDestroyed(ServletContextEvent event) {
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		InputStream input = null;
		try {
			ServletContext context = event.getServletContext();
			String fullPath = context.getRealPath("/") + "WEB-INF" + File.separator + PE_CONTROLLER_MAPPING_FILE;
			input = new FileInputStream(fullPath);
			Actions actions = (Actions) JAXBContext.newInstance(Actions.class).createUnmarshaller().unmarshal(input);

			Map<String, String> actionMappings = null;
			if (actions != null && actions.getActionControllerList() != null
					&& actions.getActionControllerList().size() > 0) {
				actionMappings = new HashMap<String, String>();
				for (ActionController actionController : actions.getActionControllerList()) {
					LOGGER.debug("Action URL [" + actionController.getUrl() + "] & Action Class [" + actionController.getPeClass() + "]") ;
					actionMappings.put(actionController.getUrl(), actionController.getPeClass());
				}
			}
			context.setAttribute("actionMappings", actionMappings);
		} catch (FileNotFoundException e) {
			LOGGER.fatal("Controller Mapping file [" + PE_CONTROLLER_MAPPING_FILE + "] not found", e);
		} catch (JAXBException e) {
			LOGGER.fatal("Invalid Mapping found inside [" + PE_CONTROLLER_MAPPING_FILE + "] file", e);
		}
	}
}
